<template>
    <div id="chinaMap"></div>
    <!-- 抽屉触发按钮 -->
    <div class="drawer-trigger" @click="drawerVisible = true">
        <el-button type="primary" :icon="Setting" circle size="large" />
    </div>

    <!-- 返回按钮 -->
    <div class="back-trigger" @click="router.back()">
        <el-button type="primary" :icon="ArrowLeftBold" circle size="large" />
    </div>

    <!-- 控制面板抽屉 -->
    <el-drawer v-model="drawerVisible" title="控制面板" direction="ltr" size="300px">
        <div class="control-panel">
            <div class="control-item">
                <div class="label">选择地理图层</div>
                <el-select v-model="selectedLayer" @change="changeLayer" placeholder="请选择图层" style="width: 100%">
                    <el-option label="矢量图" value="shiliang"></el-option>
                    <el-option label="地形图" value="dixing"></el-option>
                </el-select>
            </div>
            <div class="control-item">
                <div class="label">选择分布类型</div>
                <el-select v-model="selectedType" @change="changeType" placeholder="请选择图层" style="width: 100%">
                    <el-option label="气泡图" value="pop"></el-option>
                    <el-option label="3D柱状图" value="bar"></el-option>
                    <el-option label="水波图" value="water"></el-option>
                </el-select>
            </div>
        </div>
    </el-drawer>
</template>

<script setup>
import { GaodeMap } from '@antv/l7-maps';
import { Scene, PointLayer } from '@antv/l7';
import { Setting, ArrowLeftBold } from '@element-plus/icons-vue';
import { onMounted, ref, onUnmounted } from 'vue';

const router = useRouter();
const drawerVisible = ref(false);
const selectedLayer = ref('shiliang');
const selectedType = ref('pop');
const selectedTypeList = ref(null);
const scene = ref(null);
const pointLayerRef = ref(null);

// 切换图层
const changeLayer = (layerType) => {
    if (scene.value) {
        // 根据选择的图层类型切换地图样式
        switch (layerType) {
            case 'shiliang':
                scene.value.map.setMapStyle('amap://styles/normal');
                break;
            case 'dixing':
                scene.value.map.setMapStyle('amap://styles/whitesmoke');
                break;
            default:
                scene.value.map.setMapStyle('amap://styles/normal');
        }
    }
};

// 分布类型切换
const changeType = async (type) => {
    console.log(type);

    if (selectedTypeList.value) {
        switch (type) {
            case 'pop':
                await fetchData('https://gw.alipayobjects.com/os/basement_prod/d3564b06-670f-46ea-8edb-842f7010a7c6.json')
                break;
            case 'bar':
                await fetchData('https://gw.alipayobjects.com/os/basement_prod/893d1d5f-11d9-45f3-8322-ee9140d288ae.json');
                break;
            case 'water':
                await fetchData('https://gw.alipayobjects.com/os/basement_prod/9078fd36-ce8d-4ee2-91bc-605db8315fdf.csv', 'text');
                break;
        }
    }
};

// 更新地图类型显示
const updateMapType = async (type, url) => {
    // 移除之前的图层
    if (pointLayerRef.value && scene.value) {
        scene.value.removeLayer(pointLayerRef.value);
    }

    // 根据类型创建不同的图层
    if (type === 'pop') {
        // 气泡图
        pointLayerRef.value = new PointLayer({})
            .source(selectedTypeList.value)
            .shape('circle')
            .size('mag', [1, 25])
            .color('mag', (mag) => {
                return mag > 4.5 ? '#5B8FF9' : '#5CCEA1';
            })
            .style({
                opacity: 0.3,
                strokeWidth: 1,
            });
    } else if (type === 'bar') {
        // 3D柱状图
        pointLayerRef.value = new PointLayer({})
            .source(selectedTypeList.value, {
                parser: {
                    type: 'json',
                    x: 'longitude',
                    y: 'latitude',
                },
            })
            .animate(true)
            .active(true)
            .shape('name', ['cylinder', 'triangleColumn', 'hexagonColumn', 'squareColumn'])
            .size('unit_price', (h) => {
                return [6, 6, h / 500];
            })
            .color('name', ['#739DFF', '#61FCBF', '#FFDE74', '#FF896F']);
    } else if (type === 'water') {
        pointLayerRef.value = new PointLayer({})
            .source(selectedTypeList.value, {
                parser: {
                    type: 'csv',
                    x: 'Longitude',
                    y: 'Latitude',
                },
            })
            .shape('circle')
            .animate(true)
            .size(40)
            .color('#ffa842');
    }

    // 添加图层到场景
    if (pointLayerRef.value && scene.value) {
        scene.value.addLayer(pointLayerRef.value);
    }
};

// 获取数据
const fetchData = async (url, type = 'json') => {
    try {
        const response = await fetch(url);
        if (type === 'json') {
            selectedTypeList.value = await response.json();
        } else if (type === 'text') {
            selectedTypeList.value = await response.text();
        }
        // 默认加载气泡图
        updateMapType(selectedType.value);
    } catch (error) {
        console.error('数据加载失败:', error);
        return null;
    }
};

onMounted(() => {
    scene.value = new Scene({
        id: 'chinaMap',
        map: new GaodeMap({
            pitch: 35.210526315789465,
            style: 'dark',
            center: [104.288144, 31.239692],
            zoom: 4.4,
            token: '642143cb1def5018999a4a8ed3cf0615'
        })
    });

    scene.value.on('loaded', () => {
        fetchData('https://gw.alipayobjects.com/os/basement_prod/d3564b06-670f-46ea-8edb-842f7010a7c6.json');
    });
});

// 组件销毁时清理资源
onUnmounted(() => {
    if (scene.value) {
        scene.value.destroy();
    }
});
</script>

<style scoped lang="scss">
#chinaMap {
    position: relative;
    width: 100vw;
    height: 100vh;
    overflow: hidden;

    :deep .l7-bottom {
        display: none;
    }
}

.drawer-trigger {
    position: absolute;
    top: 20px;
    left: 80px;
    z-index: 1000;
}

.back-trigger {
    position: absolute;
    top: 20px;
    left: 20px;
    z-index: 1000;
}

.control-panel {
    .control-item {
        margin-bottom: 20px;

        .label {
            font-size: 14px;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;

            &::after {
                content: ":";
            }
        }

        &:last-child {
            margin-bottom: 0;
        }
    }
}
</style>